package com.platform.server.response;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ValidationExceptionHandler implements HandlerExceptionResolver , Ordered{
	
	private static final String MODEL_KEY="$";

	private ObjectMapper objectMapper;
	
	private Map<String,String> validationCode2ErrorCode;

	public void setValidationCode2ErrorCode(Map<String,String> validationCode2ErrorCode) {
		this.validationCode2ErrorCode = validationCode2ErrorCode;
	}

	public ObjectMapper getObjectMapper() {
		return objectMapper;
	}

	public void setObjectMapper(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		if(!(ex instanceof MethodArgumentNotValidException)){
			return null;
		}
		
		MethodArgumentNotValidException argumentException =(MethodArgumentNotValidException) ex;
		
		BindingResult result=argumentException.getBindingResult();
		
		if(result==null){
			return null;
		}
		FieldError fieldError=result.getFieldError();
		
		if(fieldError==null){
			return null;
		}
		
		String[] codes=fieldError.getCodes();
		
		int errorCode=-1;
		for(int i=0,len=codes.length;i<len;i++){
			String v=validationCode2ErrorCode.get(codes[i]);
			if(v!=null){
				errorCode=Integer.parseInt(v);
				break;
			}
		}
		MappingJackson2JsonView view=new MappingJackson2JsonView();
		view.setObjectMapper(objectMapper);
		view.setExtractValueFromSingleKeyModel(true);
		view.setModelKey(MODEL_KEY);
		ModelAndView mv=new ModelAndView();
		mv.setView(view);
		mv.getModel().put(MODEL_KEY, errorCode);
		//mv.getModel().put(MODEL_KEY, new ResultPOJO().setResultCode(errorCode));
		return mv;
	}

	@Override
	public int getOrder() {
		return 0;
	}


}
